<template>
	<view class="container" :style="{height: `calc(100vh - ${state === 1 ? '46px' : '0'})`}">
		<navBar title="施工条件验收" @goBack="uni.navigateBack()"></navBar>

		<view v-if="state === 1 && type === 3" class="tips-info">
			<view class="num required">03、</view>
			<view class="state-content">
				<view class="label">工器具、材料</view>
				<view class="details">
					确保工器具使用前的功能安全和完好性；<text style="color: #e84a4a;">施工后工器具清点，确保与进场前摆放工具一致（拍照留档）；材料堆放规范有序</text>
				</view>
			</view>
		</view>

		<view class="onditional-acceptance-image">
			<commonVideoUpload v-if="type === 5" class="video-class" titleText="班前交底(视频)"
				:disabled="loading || state === 2" :required="true" :videoFileList="fileList3" :isBlob="true"
				:playVideoSrc="playVideoSrc" @closeFile="(item, index) => removeFileByIndex('fileList3', index)"
				@clickMedias="clickMedias" @handleClickPreview="handleClickPreview"
				@closePlayVideoSrc="playVideoSrc = ''" />
			<view class="title required">
				<text v-if="titleText === '班前交底'">班前交底(图片)</text>
				<text v-else>图片</text>
				<text v-if="state === 1">（请根据红色文字提示上传图片）</text>
			</view>
			<view v-if="type === 2 || type === 3" class="tips-label">施工前</view>
			<view class="image-list">
				<view v-for="(item, index) in fileList1" :key="index" class="image-item">
					<image @click="previewImage(fileList1, index)" class="image-item" :src="item.url" mode="aspectFit">
					</image>
					<image @click="removeFileByIndex('fileList1', index)" v-if="state === 1 && type !== 3"
						src="../../../static/close.svg" class="icon"></image>
				</view>
				<view v-if="state === 1 && type !== 3" @click="chooseImage('fileList1')" class="upload-item">
					<u-icon name="camera-fill" color="#d3d4d6" size="26"></u-icon>
				</view>
			</view>
			
			<commonVideoUpload v-if="type === 4 && titleText !== '班前交底'" class="video-class" titleText="视频"
				:disabled="loading || state === 2" :videoFileList="fileList3" :isBlob="true"
				:playVideoSrc="playVideoSrc" @closeFile="(item, index) => removeFileByIndex('fileList3', index)"
				@clickMedias="clickMedias" @handleClickPreview="handleClickPreview"
				@closePlayVideoSrc="playVideoSrc = ''" />

			<template v-if="titleText == '班前交底'">
				<view class="title required">
					<text v-if="titleText === '班前交底'">每日施工任务单(图片)</text>
				</view>
				<view class="image-list">
					<view v-for="(item, index) in fileList4" :key="index" class="image-item">
						<image @click="previewImage(fileList4, index)" class="image-item" :src="item.url"
							mode="aspectFit"></image>
						<image @click="removeFileByIndex('fileList4', index)" v-if="state === 1 && type !== 3"
							src="../../../static/close.svg" class="icon"></image>
					</view>
					<view v-if="state === 1 && type !== 3" @click="chooseImage('fileList4')" class="upload-item">
						<u-icon name="camera-fill" color="#d3d4d6" size="26"></u-icon>
					</view>
				</view>
			</template>


			<template v-if="type === 2 || type === 3">
				<view class="tips-label" :class="[type === 2 ? 'forbid' : '']">
					<text>施工后</text>
					<text v-if="state === 1">（此处图片请在施工后补充）</text>
				</view>
				<view class="image-list">
					<view v-for="(item, index) in fileList2" :key="index" class="image-item">
						<image @click="previewImage(fileList2, index)" class="image-item" :src="item.url"
							mode="aspectFit"></image>
						<image @click="removeFileByIndex('fileList2', index)" v-if="state === 1 && type !== 2"
							src="../../../static/close.svg" class="icon"></image>
					</view>
					<view v-if="state === 1 && type === 3" @click="chooseImage('fileList2')"
						class="image-item upload-item">
						<u-icon name="camera-fill" color="#d3d4d6" size="26"></u-icon>
					</view>
				</view>
			</template>
		</view>
		<view style="height: 46px;"></view>
		<view v-if="state === 1" class="btn">
			<u-button :loading="loading" @click="submit" type="primary" text="确定"></u-button>
		</view>
	</view>
</template>

<script>
import {
		conditionalAcceptanceSave,
		getConditionalAcceptance,
		checkItemConfigurationList,
		doc_initMultipartUpload
	} from "@/api/conditionalAcceptance/constructionPlan.js"
	import fileMixin from "@/mixins/file.js"
	import CONFIPath from "@/config/index"
	import {getToken} from "@/utils/auth.js"
	const BASEURL = CONFIPath.BASE_URL
	export default {
		mixins: [fileMixin],
		data() {
			return {
				// 状态 - 1: 编辑  2: 查看
				state: 1,
				// 类型 - 1: 单图  2: 多图施工前  3: 多图施工后  4: 单图+视频  5: 单图+视频+任务单
				type: 1,
				// 文件列表
				fileList1: [],
				fileList2: [],
				fileList3: [],
				fileList4: [], //每日施工任务单
				deleteFiles1: [],
				deleteFiles2: [],
				deleteFiles3: [],
				deleteFiles4: [],
				loading: false,
				docId: 0,
				docId1: 0,
				docId2: 0,
				docId4: 0,
				id: 0,
				loading: false,
				playVideoSrc: '',
				titleText: '',
				chunkSize: 10 * 1024 * 1024,
				fileIndex: 1
			}
		},
		async onLoad(options) {
			this.state = Number(options.state)
			this.type = Number(options.type)
			this.docId = Number(options.docId)
			this.docId1 = Number(options.docId1)
			this.docId2 = Number(options.docId2)
			this.docId4 = Number(options.docId4)
			this.titleText = options.titleText
			this.id = Number(options.id)
			if (this.docId) {
				this.getFileListByDocId(this.docId).then(res => {
					this.fileList1 = res
				})
			}
			if (this.docId1) {
				this.getFileListByDocId(this.docId1).then(res => {
					this.fileList2 = res
				})
			}
			if (this.docId2) {
				this.getFileListByDocId(this.docId2).then(res => {
					this.fileList3 = res
				})
			}
			if (this.docId4) {
				this.getFileListByDocId(this.docId4).then(res => {
					this.fileList4 = res
				})
			}
			// 待完善
			if (this.type === 3 && this.id) {
				await this.checkItemConfigurationList()
				this.getConditionalAcceptance()
			}
		},
		methods: {
			chooseImage(key) {
				if (this.loading) {
					return
				}
				uni.chooseImage({
					count: 9,
					sourceType: ['album'],
					success: res => {
						this[key] = this[key].concat(res.tempFilePaths.map(item => ({
							url: item
						})))
					}
				});
			},
			uploadFile() {
				return new Promise(async (resolve, reject) => {
					if (this.fileList1.length) {
						const array = this.fileList1.filter(item => !item.id)
						this.docId = await this.uploadFileList(array, this.docId, {expiredTime:24 * 60 * 60 * 1000 * 90})
					}
					if (this.fileList2.length) {
						const array = this.fileList2.filter(item => !item.id)
						this.docId1 = await this.uploadFileList(array, this.docId1, {expiredTime:24 * 60 * 60 * 1000 * 90})
					}
					if (this.fileList4.length) {
						const array = this.fileList4.filter(item => !item.id)
						this.docId4 = await this.uploadFileList(array, this.docId4, {expiredTime:24 * 60 * 60 * 1000 * 90})
					}
					if (this.fileList3.length) {
						const array = this.fileList3.filter(item => !item.id)
						// if(array.length > 1)  return this.$message('单次只能上传一个大文件')
						try {
							// #ifdef APP-PLUS || H5
								this.docId2 = await this.uploadFileList(array, this.docId2, undefined, {timeout: 6 * 1000 * 10 })
							// #endif
							// #ifdef MP-WEIXIN
								await this.uploadPart()
							// #endif
						} catch (err) {
							uni.showToast({
								title: '上传文件超时,此次上传失败！',
								icon: "none"
							})
							this.fileList3 = []
							reject()
							return
						}
					}
					resolve()
				})
			},
			async submit() {
				if (this.loading) {
					return
				}
				this.loading = true

				if (this.type !== 3) {
					if (!this.fileList1.length && this.type !== 4) {
						uni.showToast({
							title: `请上传${this.type === 2 ? '施工前' : ''}图片`,
							icon: "none"
						})
						this.loading = false
						return
					} else if (this.type === 5 && this.titleText === '班前交底' && (!this.fileList3.length || !this
							.fileList1.length || !this.fileList4.length)) {
						uni.showToast({
							title: `请上传${this.type === 2 ? '施工前' : ''}图片或视频`,
							icon: "none"
						})
						this.loading = false
						return
					} else if (this.type === 4 && !this.fileList1.length && !this.fileList3.length) {
						uni.showToast({
							title: `请上传${this.type === 2 ? '施工前' : ''}图片或视频`,
							icon: "none"
						})
						this.loading = false
						return
					}

					await this.deleteFiles()
					try {
						await this.uploadFile()
						this.$$emit("_changeState", {
							docId: this.docId,
							docId2: this.docId2,
							docId4: this.docId4
						})
						uni.navigateBack()
						this.loading = false
					} catch (err) {} finally {
						this.loading = false
					}
				} else {
					if (!this.fileList2.length) {
						uni.showToast({
							title: "请上传施工后图片",
							icon: "none"
						})
						this.loading = false
						return
					}
					try {
						await this.deleteFiles()
						await this.uploadFile()
						await this.conditionalAcceptanceSave()
						uni.showToast({
							title: "提交成功",
							icon: "none"
						})
						const tiemout = setTimeout(() => {
							clearTimeout(tiemout)
							uni.navigateBack()
							this.loading = false
						}, 500)
					} catch (e) {
						uni.showToast({
							title: "提交失败，请重新尝试",
							icon: "none"
						})
						this.loading = false
					}
				}
			},
			checkItemConfigurationList() {
				checkItemConfigurationList({
					currPage: 1,
					pageSize: 20,
					params: {}
				}).then(res => {
					if (res && res.result && res.result.list) {
						this.configurationList = res.result.list
					}
				})
			},
			getConditionalAcceptance() {
				getConditionalAcceptance({
					id: this.id
				}).then(res => {
					if (res && res.result && Array.isArray(res.result.conditionalAcceptanceList)) {
						const tempArray = res.result.conditionalAcceptanceList.filter(item => {
							const temp = this.configurationList.find(item1 => item1.id === item
								.checkItemConfigurationId)
							return temp && temp.titleText.indexOf('工器具、材料') !== -1
						})
						const data = tempArray[0] || {}
						if (data.docId) {
							for (const item of this.configurationList) {
								if (item.id === data.checkItemConfigurationId) {
									this.configuration = {
										...item,
										...data,
										id: item.id,
										_id: data.id
									}
								}
							}
							this.docId = data.docId
							this.getFileListByDocId(this.docId).then(res => {
								this.fileList1 = res
							})
						}
					}
				})
			},
			conditionalAcceptanceSave() {
				let resq = {
					ConstructionPlanId: this.id,
					conditionalAcceptances: [{
						conditionalAcceptanceFileList: [],
						constructionPlanId: this.id,
						docId: this.docId ? this.docId : undefined,
						doc1Id: this.type === 3 ? this.docId1 : undefined,
						checkItemConfigurationId: this.configuration.id,
						name: this.configuration.name,
						content: this.configuration.content ? this.configuration.content : undefined,
						code: this.configuration.code,
						status: this.configuration.status,
						id: this.configuration._id
					}],
					isSave: false
				}
				// console.log(resq, '入参--')
				// return
				return new Promise(resolve => {
					conditionalAcceptanceSave(resq).finally(() => {
						resolve()
					})
				})
			},
			previewImage(fileList, index) {
				uni.previewImage({
					urls: fileList.map(item => item.url),
					current: index
				})
			},
			async deleteFiles() {
				const array = [...this.deleteFiles1, ...this.deleteFiles2, ...this.deleteFiles3, ...this.deleteFiles4]
				try {
					await Promise.all(array.map(item => this.removeFileById(item)))
				} catch (e) {}
			},
			removeFileByIndex(key, index) {
				if (key === 'fileList1' && this[key][index].id) {
					this.deleteFiles1.push(this[key][index].id)
				}
				if (key === 'fileList2' && this[key][index].id) {
					this.deleteFiles2.push(this[key][index].id)
				}
				if (key === 'fileList3' && this[key][index].id) {
					this.deleteFiles3.push(this[key][index].id)
				}
				if (key === 'fileList4' && this[key][index].id) {
					this.deleteFiles4.push(this[key][index].id)
				}
				this[key].splice(index, 1)
			},
			previewVideo(item) {
				if (item.url.startsWith("_doc")) {
					item.url = 'file://' + plus.io.convertLocalFileSystemURL(item.url);
				}
				this.playVideoSrc = item.url;
			},
			/** 预览文件 */
			handleClickPreview(item) {
				console.log(item, '点击视频');
				if (item.url.startsWith("_doc")) {
					item.url = 'file://' + plus.io.convertLocalFileSystemURL(item.url);
				}
				this.playVideoSrc = item.url;
			},
			async clickMedias(e) {
				if(this.state == 2) {
					return
				}
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					compressed: true,
					success: res => {
						// #ifdef APP-PLUS
							const maxSize = 1024 * 1024 * 800  //app最大文件为800兆 超出时提示到小程序上传
							if (parseInt(res.size) > maxSize) {
								return uni.showToast({
									title: '视频过大，请在小程序上传！',
									icon: 'none',
									mask: true
								})
							}
						// #endif
						this.fileList3.push({...res ,url: res.tempFilePath,type: "video"})
						const array = this.fileList3.filter(item => !item.id)
						if(array.length > 1)  {
							this.$message('单次只能上传一个大文件')
							this.fileList3.pop()
							return 
						}
					}
				});
			},
			splitFileIntoChunks(filePath, fileSize, data) {
				this.fileChunks = [];
				for (let i = 0; i < this.totalChunks; i++) {
					const start = i * this.chunkSize;
					const end = Math.min(start + this.chunkSize, fileSize);
					console.log(end, 'end')
					//读取本地文件内容  ArrayBuffer 格式
					uni.getFileSystemManager().readFile({
						filePath,
						position: start,
						length: end - start,
						success: (a) => {
							console.error('aaaaa', a)
							let fs = uni.getFileSystemManager()
							let indexFileName = i + '_wxtest.mp4'
							//写入文件
							fs.writeFile({
								filePath: `${wx.env.USER_DATA_PATH}/${indexFileName}`,
								data: a.data,
								encoding: 'utf-8',
								success: (b) => {
									console.error(b)
									this.fileChunks[i] = {
										idx: i,
										name: `${wx.env.USER_DATA_PATH}/${indexFileName}`
									};
									if (this.fileChunks.filter(it => it).length == this.totalChunks) {
										this.loading = true
										this.uploadFileTest3(data).then(del => {
											console.error('进入del')
											this.loading = true
											this.removeForFile()
										})
									}
								}
							})
						}
					})
				}
			},
			//循环删除本地缓存文件
			removeForFile(){
				let fs = uni.getFileSystemManager()
				for(let item of this.fileChunks) {
					fs.unlink({
						filePath:item.name,
						success:(re)=> {
							console.error('删除成功', re)
						},
						fail:(err) => {
							console.error('删除失败',err)
						}
					})
				}
			},
			uploadFileTest3(data) {
				//先定义一个promise数组
				let promiseArray = []
				for (let item of this.fileChunks) {
					const formData = {
						chunkIndex: item.idx + 1,
						uploadId: data.uploadId,
						id: data.id
					};
					let promiseItem = new Promise(resolve => {
						uni.uploadFile({
							url: BASEURL + 'rest/doc/uploadPart', // 替换为你的上传接口地址
							filePath: item.name,
							name: 'chunk',
							header: {
								'x-auth-token': getToken()
							},
							formData,
							success: (test3Res) => {
								console.error('test3Res', test3Res)
								resolve()
							}
						});
					})
					promiseArray.push(promiseItem)
				}
				return Promise.all(promiseArray)
			},
			generateRandomCode(length) {
			  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
			  var code = '';
			  for (var i = 0; i < length; i++) {
				code += chars.charAt(Math.floor(Math.random() * chars.length));
			  }
			  return code;
			},
			// 上传初始化接口
			initUpload(obj) {
				console.error('啥子东西', obj)
				return new Promise(resolve => {
					doc_initMultipartUpload({
						fileName: this.generateRandomCode(18) + '.mp4',
						length: obj.size,
						chunkSize: 10 * 1024 * 1024,
						docInfoId: obj.docInfoId ? obj.docInfoId : undefined // 这里是一个
					}).then(res => {
						resolve(res)
					})
				})
			},
			async uploadPart() {
				// 获取需要上传的文件列表
				const fileList = this.fileList3.filter(item => !item.id)
				// 判断是否有docId，没有则先上传一个文件并获取docId
				if (!this.docId2) {
					const file = fileList[0]
					console.error(file, '文件信息-----')
					let response = await this.initUpload(file)
					// 调用init方法获取到docId
					this.docId2 = response.result.docInfoId
					// #ifdef MP-WEIXIN
						const fs = uni.getFileSystemManager()
						fs.getFileInfo({
							filePath: file.url,
							success: fileInfo => {
								// 计算切片数量
								this.totalChunks = Math.ceil(fileInfo.size / this.chunkSize);
								// 将文件切割为多个切片
								this.splitFileIntoChunks(file.tempFilePath, fileInfo.size, response.result);
							}
						})
					// #endif
					fileList.splice(0, 1)
				}
				// 其余文件上传至docId上
				for (const item of fileList) {
					// 首先init方法 
					this.initUpload(Object.assign(item, {docInfoId: this.docId2})).then(res => {
						// #ifdef MP-WEIXIN
							const fs = uni.getFileSystemManager()
							fs.getFileInfo({
								filePath: item.tempFilePath,
								success: fileInfo => {
									// 计算切片数量
									this.totalChunks = Math.ceil(fileInfo.size / this.chunkSize);
									// 将文件切割为多个切片
									this.splitFileIntoChunks(item.tempFilePath, fileInfo.size, res.result);
								}
							})
						// #endif
					})
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		box-sizing: border-box;
		overflow-y: auto;
		/* #ifdef MP-WEIXIN */
		padding-top: 200rpx;
		/* #endif */
	}

	.onditional-acceptance-image {
		font-size: 16px;
		font-weight: bold;
		border-top: 15px solid #f5f7fa;
		padding: 0 4px 0 14px;
		height: 100%;

		.title {
			line-height: 50px;
			margin-top: 5px;

			text:nth-of-type(1) {
				color: #445469;
			}

			text:nth-of-type(2) {
				color: #768293;
			}
		}

		.tips-label {
			margin: 6px 0 10px;
			line-height: 22px;
			font-weight: bold;
			color: #445469;

			&.forbid {
				color: #c7c7c7;
			}
		}

		.image-list {
			display: inline-flex;
			flex-wrap: wrap;

			.image-item {
				margin-right: 12px;
				margin-bottom: 12px;
				width: 96px;
				height: 96px;
				border-radius: 4px;
				background: rgba(0, 0, 0, .75);
				position: relative;

				.icon {
					width: 18px;
					height: 18px;
					top: -9px;
					right: -9px;
					position: absolute;
					z-index: 1;
					background: #fff;
					border-radius: 50%;
				}
			}

			.upload-item {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-right: 12px;
				margin-bottom: 12px;
				width: 96px;
				height: 96px;
				border-radius: 4px;
				background: #f4f5f7;

				image {
					width: 30px;
					height: 30px;
				}
			}
		}
	}

	.required {
		&::before {
			content: "*";
			color: #ff4646;
			font-size: 16px;
			line-height: 29px;
		}
	}

	.tips-info {
		height: 156px;
		display: flex;
		padding: 17px 15px 13px;
		box-sizing: border-box;
		border-top: 15px solid #f5f7fa;

		.num {
			width: 41px;
			flex-shrink: 0;
			color: #22204e;
			font-weight: bold;
			line-height: 29px;
		}

		.state-content {
			flex: 1;

			.label {
				line-height: 29px;
				color: #22204e;
				font-weight: bold;
			}
		}

		.details {
			line-height: 22px;
			margin-top: 9px;
			color: #778599;
			font-size: 14px;
			font-weight: bold;
		}
	}

	.btn {
		position: fixed;
		bottom: 0;
		width: 100vw;
		padding: 0 15px;
		box-sizing: border-box;
		height: 46px;

		>* {
			height: inherit;
			line-height: 46px;
		}
	}

	.video-class {
		::v-deep .photo-list {
			margin-left: 0;
		}

		::v-deep .video-item {
			width: 96px !important;
			height: 96px !important;
			border-radius: 4px !important;
			margin-right: 12px !important;
			margin-bottom: 12px !important;
			overflow: hidden !important;

			.upload-video-item {
				width: 100% !important;
				height: 100% !important;
			}
		}
	}
</style>